<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Number implements Rule
{
    private $decimals;
    /**
     * @var int
     */
    private $integer;

    /**
     * Create a new rule instance.
     *
     * @param int $integer 整数位
     * @param int $decimals 小数位
     */
    public function __construct(int $integer, int $decimals = 0)
    {
        $this->decimals = $decimals;
        $this->integer = $integer;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        list($integer, $decimals) = array_pad(explode('.', $value, 2), 2, '');

        if ($this->integer >= strlen($integer)) {
            return $this->decimals >= strlen($decimals);
        }
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute 最长只能' . $this->integer . '位整数, 最长只能' . $this->decimals . '位小数';
    }
}
